<template>
  <el-dialog :title="title" v-model="isShow" width="45%" @close="closeHandler" draggable="true">
    <el-form :model="formData" :rules="formRules" ref="formRef" label-width="120px" :inline="false">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="formData.name"></el-input>
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input v-model="formData.description"></el-input>
      </el-form-item>
      <el-form-item label="权限标识" prop="menus">
        <el-tree :data="userInfo" show-checkbox="true" node-key="id" :default-expanded-keys="[]"
          :default-checked-keys="formData.menus" :props="props" ref="tree" />
      </el-form-item>
      <el-form-item label="启用状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :label="0">禁用</el-radio>
          <el-radio :label="1">启用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="onSubmit">确定</el-button>
    <el-button type="primary" plain @click="isShow = false">取消</el-button>
  </el-dialog>
</template>
<script setup>
import { ref, computed, toRaw, onMounted } from 'vue'
import { addRoleApi, editRoleInfoApi } from '../../../api/auth.js'
import { ElMessage } from "element-plus";
import { useReplayData } from '../../../xf-hook/editDel'
const replateForm = useReplayData()
const isShow = ref(false)
const tree = ref();
const defaultState = {
  description: "",
  menus: [],
  name: "",
  status: 1,
  id: null
}
const emit = defineEmits(["updateList"]);
const formRules = {
  description: [{ required: true, message: "请选择", trigger: "blur" }],
  name: [{ required: true, message: "请选择", trigger: "blur" }],
  status: [{ required: true, message: "请选择", trigger: "blur" }],
  menus: [{ required: true, message: "请选择", trigger: "change" }],
};
const formRef = ref()
const onSubmit = async () => {
  try {

    formData.menus = tree.value.getCheckedKeys()
    const data = toRaw(formData);
    // await addRoleApi(data)
    await formRef.value.validate();
    formData.id ? await editRoleInfoApi(data) : await addRoleApi(data)
    ElMessage.success("操作成功");
    isShow.value = false;
    emit("updateList");
  } catch (error) {
    console.log(error);
  }
};
onMounted(() => {
})
defineProps({
  userInfo: {
    type: Array,
    default: () => []
  },
  props: {
    type: Object,
    default: () => { }
  }
})
const formData = reactive({ ...defaultState });
const replyData = (id) => {
  isShow.value = true
  replateForm.replayData(id, formData)
}
const closeHandler = () => {
  // 移除校验
  formRef.value.resetFields()
  tree.value.setCheckedKeys([]);
  // 重置表单数据
  Object.assign(formData, { ...defaultState })
  formData.menus.value = []
};
const title = computed(() => {
  return formData.id ? '修改' : '新增'
})
defineExpose({
  isShow,
  formData,
  replyData
});
</script>